import { Injectable } from '@nestjs/common'
import { PassportStrategy } from '@nestjs/passport'
import { ExtractJwt, Strategy } from "passport-jwt"
import { jwtConstants } from "@constants/jwt.constant";
import { AuthService } from "@/modules/auth/auth.service";
import { CacheService } from "@cache";
import { CacheKeyConstant } from "@constants/cache.key.constant";
import { AuthException } from "@exceptions";

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
    constructor(
        private cacheService: CacheService
    ) {
        super({
            jwtFromRequest: ExtractJwt.fromHeader('access_token'), //使用ExtractJwt.fromHeader从header获取token,
            ignoreExpiration: false,
            secretOrKey: jwtConstants.secret
        })
    }

    async validate(payload: any) {
        console.log('jwt---validate,', payload)
        if (payload) {
            /**
             * 1、如果redis中token不存在，则认为退出登录、修改信息、
             * 2、同时当前登录用户是否在redis中存在，不存在则已经退出登录了
             */
            const cacheToken: string = await this.cacheService.get(`${CacheKeyConstant.AUTH_USER_TOKEN}${payload.userId}`)
            const onlineUsers: Array<number> = await this.cacheService.get(`${CacheKeyConstant.SYS_ONLINE_USERS}`)
            if (!(cacheToken && onlineUsers.includes(+payload.userId))) {
                throw new AuthException()
            }
        }
        // 这里会拿到模块解析token之后的用户信息（如果一切正常的话）
        return payload;
    }
}
